package com.sys.service.impl;

import com.sys.config.OssConfig;
import com.sys.dto.CheckInRequest;
import com.sys.entity.BizTaskLog;
import com.sys.entity.BizTaskPhoto;
import com.sys.mapper.BizPlanItemMapper;
import com.sys.mapper.BizTaskLogMapper;
import com.sys.mapper.BizTaskPhotoMapper;
import com.sys.service.TaskLogService;
import com.sys.utils.OssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Slf4j
@Service
public class TaskLogServiceImpl implements TaskLogService {

    @Autowired
    private BizTaskLogMapper taskLogMapper;

    @Autowired
    private BizTaskPhotoMapper taskPhotoMapper;

    @Autowired
    private BizPlanItemMapper planItemMapper;

    @Autowired
    private OssConfig ossConfig;

    @Autowired
    private OssUtil ossUtil;

    // 本地存储目录
    private final String UPLOAD_DIR = "uploads/";

    @Transactional
    @Override
    public BizTaskLog checkIn(CheckInRequest checkInRequest, MultipartFile photoFile) {
        BizTaskLog taskLog = new BizTaskLog();
        taskLog.setUserId(checkInRequest.getUserId());
        taskLog.setTaskId(checkInRequest.getTaskId());
        taskLog.setPlanItemId(checkInRequest.getPlanItemId());
        taskLog.setRemarks(checkInRequest.getRemarks());
        taskLog.setScore(checkInRequest.getScore());
        taskLog.setStatus(1); // 1 for completed
        taskLog.setLoggedAt(LocalDateTime.now());

        if (photoFile != null && !photoFile.isEmpty()) {
            taskLog.setPhotosCount(1);
        } else {
            taskLog.setPhotosCount(0);
        }

        taskLogMapper.save(taskLog);

        // 更新计划项状态为已完成
        if (checkInRequest.getPlanItemId() != null) {
            log.info("打卡成功，更新计划项状态：planItemId={}, status=1", checkInRequest.getPlanItemId());
            planItemMapper.updateStatus(checkInRequest.getPlanItemId(), 1, LocalDateTime.now());
        }

        if (photoFile != null && !photoFile.isEmpty()) {
            try {
                String photoPath;
                
                // 根据配置选择上传方式
                if (ossConfig.isEnabled()) {
                    // 使用OSS上传
                    log.info("使用阿里云OSS上传文件");
                    photoPath = ossUtil.uploadFile(photoFile, checkInRequest.getUserId());
                } else {
                    // 使用本地存储
                    log.info("使用本地存储上传文件");
                    photoPath = savePhotoToLocal(photoFile, checkInRequest.getUserId());
                }
                
                BizTaskPhoto photo = new BizTaskPhoto();
                photo.setTaskLogId(taskLog.getId());
                photo.setFilePath(photoPath);
                photo.setFileName(photoFile.getOriginalFilename());
                photo.setFileSize((int) photoFile.getSize());
                photo.setMimeType(photoFile.getContentType());
                taskPhotoMapper.save(photo);
            } catch (IOException e) {
                log.error("保存照片失败: {}", e.getMessage(), e);
                throw new RuntimeException("保存照片失败: " + e.getMessage(), e);
            }
        }

        return taskLog;
    }

    /**
     * 保存照片到本地存储
     *
     * @param file   文件
     * @param userId 用户ID
     * @return 文件相对路径
     * @throws IOException IO异常
     */
    private String savePhotoToLocal(MultipartFile file, Long userId) throws IOException {
        // 创建用户目录（如果不存在）
        String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        Path userUploadPath = Paths.get(UPLOAD_DIR, "user_" + userId, date);
        if (!Files.exists(userUploadPath)) {
            Files.createDirectories(userUploadPath);
        }

        // 创建唯一文件名避免冲突
        String originalFileName = file.getOriginalFilename();
        String fileExtension = "";
        if (originalFileName != null && originalFileName.contains(".")) {
            fileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));
        }
        String newFileName = System.currentTimeMillis() + fileExtension;

        // 保存文件
        Path filePath = userUploadPath.resolve(newFileName);
        Files.copy(file.getInputStream(), filePath);

        // 返回相对路径存储到数据库
        return filePath.toString().replace(File.separator, "/");
    }
}